﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using G.WeiBo.View.ChildWindows;
using System.Text.RegularExpressions;
using System.Linq;
using System.Collections.Generic;

namespace G.WeiBo.LoacalControls
{
    public class FormatTextBlock : ContentControl
    {
        private static readonly Regex _parseHashtags = new Regex("[#][A-Za-z0-9\\s?“,.;:\"\\]\\[~!*&^%$一-龥]+[#]", RegexOptions.IgnoreCase);
        private static readonly Regex _parseMentions = new Regex(@"[@](?!\w+\.[A-Za-z0-9\-_\u4e00-\u9fa5]+)(\w|-)+", RegexOptions.IgnoreCase);
        private static readonly Regex _parseUrls = new Regex(@"[http|https|ftp]+://([a-zA-Z_0-9]+\.)+[a-zA-Z_0-9]+(/[a-zA-Z_0-9./?%&=a-zA-Z_0-9]*)?", RegexOptions.IgnoreCase);


        private class LinkData
        {
            public int Type { get; set; }
            public string Data { get; set; }
        }
        private static void SetLinkButton(Paragraph p, LinkData linkdata)
        {
            Brush brush = Application.Current.Resources["PhoneAccentBrush"] as Brush;
            Hyperlink btn = new Hyperlink { Foreground = brush };
            switch (linkdata.Type)
            {
                case 0:
                    btn.Click += (_s, _e) =>
                    {
                        Navigate.NavigationService.Navigate("/View/TopicBrowserPage.xaml?topicName=" + linkdata.Data.Substring(1, linkdata.Data.Length - 2), null);
                    };
                    break;
                case 1:
                    btn.Click += (_s, _e) =>
                    {
                        BrowserWebChildWindow task = new BrowserWebChildWindow(linkdata.Data);
                        task.IsOpen = true;
                    };
                    break;

                case 2:
                    btn.Click += (_s, _e) =>
                    {
                        Navigate.NavigationService.Navigate("/View/UserInfoPage.xaml?username=" + linkdata.Data.Substring(1, linkdata.Data.Length - 1), null);
                    };
                    break;

            }
            btn.Inlines.Add(linkdata.Data);
            p.Inlines.Add(btn);
        }
        public static readonly DependencyProperty TextPropertey = DependencyProperty.Register("Text", typeof(string), typeof(FormatTextBlock), new PropertyMetadata(string.Empty, (s, e) =>
        {
            RichTextBox txt = new RichTextBox { TextWrapping = System.Windows.TextWrapping.Wrap, Foreground = Application.Current.Resources["PhoneForegroundBrush"] as Brush };
            txt.IsReadOnly = true;
            Paragraph p = new Paragraph();
            txt.Blocks.Add(p);
            string message = e.NewValue as string;
            var topics = _parseHashtags.Matches(message);
            (s as FormatTextBlock).Content = txt;
            var mentions = _parseMentions.Matches(message);
            var urls = _parseUrls.Matches(message);
            List<LinkData> list = new List<LinkData>();
            foreach (var t in topics)
                list.Add(new LinkData { Data = t.ToString(), Type = 0 });
            foreach (var u in urls)
                list.Add(new LinkData { Data = u.ToString(), Type = 1 });

            foreach (var m in mentions)
                list.Add(new LinkData { Data = m.ToString(), Type = 2 });
            Dictionary<int, LinkData> dic = new Dictionary<int, LinkData>();
            foreach (var str in list)
            {
                int num = -1;
                do
                {
                    num = message.IndexOf(str.Data, num + 1);
                } while (dic.ContainsKey(num));
                dic.Add(num, str);

            }
            var tempDic = dic.OrderBy(c => c.Key);

            string[] strs = message.Split(tempDic.Select(c => c.Value.Data).ToArray(), StringSplitOptions.None);
            int i = 0;
            foreach (var t in tempDic)
            {
                if (t.Key == 0)
                {
                    SetLinkButton(p, t.Value);
                    p.Inlines.Add(strs[i]);
                }
                else
                {
                    p.Inlines.Add(strs[i]);
                    SetLinkButton(p, t.Value);
                }
                i++;
            }
            p.Inlines.Add(strs[i]);
        }));
        public string Text
        {
            get
            {
                return (string)this.GetValue(TextPropertey);
            }
            set
            {
                this.SetValue(TextPropertey, value);
            }
        }
        public FormatTextBlock()
        {
            //this.
        }
    }

}
